package app.ui;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.TextView;
import android.widget.ToggleButton;
import app.ui.SessionEvents.AuthListener;
import app.ui.SessionEvents.LogoutListener;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.Facebook;
import com.facebook.android.R;

import database.local.Business;
import database.local.PicturesUtil;
import database.local.PreferencesSyncronizer;

public class PreferencesActivity extends Activity {

	public static final String APP_ID = AndroAppActivity.APP_ID;
	String[] permissions = { "offline_access", "user_photos",
			"publish_checkins", "friends_checkins", "publish_actions",
			"publish_stream", "read_stream", "user_likes", "user_interests" };

	private RatingBar rating_thr_ratingbar;
	private RatingBar money_thr_ratingbar;
	private LoginButton login_button_btn;
	private ToggleButton pubToggleButton, restToggleButton, partyToggleButton;
	private TextView facebook_text_txt, userNameText, userDealText,
			userLikesText;
	public ImageView mUserPic;
	public ListView myDealsList;
	private PreferencesSyncronizer dbc;

	private ViewGroup userDetailsLayout;
	public List<Business> business_list;
	private Handler mHandler;

	private Facebook mFacebook;
	private AsyncFacebookRunner mAsyncRunner;

	private String facebook_user;
	private String facebook_mail;
	

	private boolean isEatVisible, isDrinkVisible, isPartyVisible;

	public static final String PREF_FACEBOOK_USER = "PREF_FACEBOOK_USER";
	public static final String PREF_FACEBOOK_MAIL = "PREF_FACEBOOK_MAIL";
	public static final String PREF_RATING_THREHOLD = "PREF_RATING_THREHOLD";
	public static final String PREF_MONEY_THREHOLD = "PREF_MONEY_THREHOLD";
	public static final String PROFILE_PIC_URL = "PROFILE_PIC_URL";
	public static final String PROFILE_PIC_URL_SMALL = "PROFILE_PIC_URL_SMALL";
	public static final String PREF_FACEBOOK_PAGE_URL = "PREF_FACEBOOK_PAGE_URL";
	public static final String PREF_DRINK_BUTTON_VISIBLE = "PREF_DRINK_BUTTON_VISIBLE";
	public static final String PREF_EAT_BUTTON_VISIBLE = "PREF_EAT_BUTTON_VISIBLE";
	public static final String PREF_PARTY_BUTTON_VISIBLE = "PREF_PARTY_BUTTON_VISIBLE";
	public static final String PREF_CHANGED = "PREF_CHANGED";
	public static final String PREF_LIKES = "PREF_LIKES";

	SharedPreferences prefs;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.preferences);

		dbc = new PreferencesSyncronizer(this);

		login_button_btn = (LoginButton) findViewById(R.id.login_button_btn);
		facebook_text_txt = (TextView) findViewById(R.id.preferences_facebook_txt);
		userDealText = (TextView) findViewById(R.id.preferences_user_deals_text);
		userLikesText = (TextView) findViewById(R.id.preferences_user_likes_text);
		userNameText = (TextView) findViewById(R.id.preferences_user_name_text);
		userDetailsLayout = (ViewGroup) findViewById(R.id.preferences_user_details_layout);

		rating_thr_ratingbar = (RatingBar) findViewById(R.id.preferences_rating_thr_ratingbar);
		rating_thr_ratingbar.setOnRatingBarChangeListener(new OnRatingBarChangeListener(){
			public void onRatingChanged(RatingBar ratingBar, float rating,
					boolean fromUser) {
				Editor editor = prefs.edit();
				editor.putInt(PREF_RATING_THREHOLD, (int)rating);
				editor.putBoolean(PREF_CHANGED, true);
				editor.commit();
			}
		});
		
		money_thr_ratingbar = (RatingBar) findViewById(R.id.preferences_money_thr_ratingbar);
		money_thr_ratingbar.setOnRatingBarChangeListener(new OnRatingBarChangeListener(){
			public void onRatingChanged(RatingBar ratingBar, float rating,
					boolean fromUser) {
				Editor editor = prefs.edit();
				editor.putInt(PREF_MONEY_THREHOLD, (int)rating);
				editor.putBoolean(PREF_CHANGED, true);
				editor.commit();
			}
		});
		mUserPic = (ImageView) findViewById(R.id.user_pic);

		// Start facebook sycronization
		mFacebook = new Facebook(APP_ID);
		mAsyncRunner = new AsyncFacebookRunner(mFacebook);

		SessionStore.restore(mFacebook, this);
		SessionEvents.addAuthListener(new SampleAuthListener());
		SessionEvents.addLogoutListener(new SampleLogoutListener());
		login_button_btn.init(this, mFacebook, permissions);

		// update UI from previous settings
		Context context = getApplicationContext();
		prefs = PreferenceManager.getDefaultSharedPreferences(context);

//		// OK button
//		Button okButton = (Button) findViewById(R.id.preferences_okButton);
//		okButton.setOnClickListener(new View.OnClickListener() {
//			public void onClick(View view) {
//				savePreferences();
//				PreferencesActivity.this.setResult(RESULT_OK);
//				finish();
//			}
//		});
//
//		// Cancel button
//		Button cancelButton = (Button) findViewById(R.id.preferences_cancelButton);
//		cancelButton.setOnClickListener(new View.OnClickListener() {
//			public void onClick(View view) {
//				PreferencesActivity.this.setResult(RESULT_CANCELED);
//				finish();
//			}
//		});

		// Pub toggle button
		pubToggleButton = (ToggleButton) findViewById(R.id.preferences_pub_toggle_button);
		pubToggleButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				if (pubToggleButton.isChecked()) {
					isDrinkVisible = true;
				} else {
					isDrinkVisible = false;
				}
				Editor editor = prefs.edit();
				editor.putBoolean(PREF_DRINK_BUTTON_VISIBLE, isDrinkVisible);
				editor.putBoolean(PREF_CHANGED, true);
				editor.commit();
			}
		});

		// Rest toggle button
		restToggleButton = (ToggleButton) findViewById(R.id.preferences_rest_toggle_button);
		restToggleButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				if (restToggleButton.isChecked()) {
					isEatVisible = true;
				} else {
					isEatVisible = false;
				}
				Editor editor = prefs.edit();
				editor.putBoolean(PREF_EAT_BUTTON_VISIBLE, isEatVisible);
				editor.putBoolean(PREF_CHANGED, true);
				editor.commit();
			}
		});

		// party toggle button
		partyToggleButton = (ToggleButton) findViewById(R.id.preferences_party_toggle_button);
		partyToggleButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				if (partyToggleButton.isChecked()) {
					isPartyVisible = true;
				} else {
					isPartyVisible = false;
				}
				Editor editor = prefs.edit();
				editor.putBoolean(PREF_PARTY_BUTTON_VISIBLE, isPartyVisible);
				editor.putBoolean(PREF_CHANGED, true);
				editor.commit();
			}
		});

		updateUIFromPreferences();

		myDealsList = (ListView) findViewById(R.id.preferences_my_list);
		if (mFacebook != null && mFacebook.isSessionValid()) {
			Log.w("Preferences", "Calling sync");
			dbc.sync(facebook_mail);
		}

		myDealsList
				.setOnItemClickListener(new AdapterView.OnItemClickListener() {
					public void onItemClick(AdapterView<?> parentView,
							View childView, int position, long id) {
						
						final int p = position;
						AlertDialog.Builder builder = new AlertDialog.Builder(PreferencesActivity.this);
						builder.setMessage("You are going to delete this deal. Are you sure?")
								.setPositiveButton("Ok",
										new DialogInterface.OnClickListener() {
											public void onClick(DialogInterface dialog,
													int id) {
												dbc.delete(facebook_mail, business_list.get(p));
												business_list.remove(p);
												setUserDealsText(business_list.size());
												myDealsList.setAdapter(new BusinessListArrayAdapter(PreferencesActivity.this, business_list));
											}
										})
								.setNegativeButton("Cancel",
										new DialogInterface.OnClickListener() {
											public void onClick(DialogInterface dialog,
													int id) {
												return;
											}
										}).show();
					}
				});
	}

	private void updateUIFromPreferences() {
		facebook_user = prefs.getString(PREF_FACEBOOK_USER, "");
		facebook_mail = prefs.getString(PREF_FACEBOOK_MAIL, "");
		int ratingThr = prefs.getInt(PREF_RATING_THREHOLD, 3);
		int moneyThr = prefs.getInt(PREF_MONEY_THREHOLD, 2);
		String picURL = prefs.getString(PROFILE_PIC_URL, null);
		rating_thr_ratingbar.setRating(ratingThr);
		money_thr_ratingbar.setRating(moneyThr);
		isDrinkVisible = prefs.getBoolean(PREF_DRINK_BUTTON_VISIBLE, true);
		isEatVisible = prefs.getBoolean(PREF_EAT_BUTTON_VISIBLE, true);
		isPartyVisible = prefs.getBoolean(PREF_PARTY_BUTTON_VISIBLE, true);
		
		Editor editor = prefs.edit();
		editor.putBoolean(PREF_CHANGED, false);
		editor.commit();

		if (isDrinkVisible)
			pubToggleButton.setChecked(true);
		else
			pubToggleButton.setChecked(false);

		if (isEatVisible)
			restToggleButton.setChecked(true);
		else
			restToggleButton.setChecked(false);

		if (isPartyVisible)
			partyToggleButton.setChecked(true);
		else
			partyToggleButton.setChecked(false);

		if (mFacebook.isSessionValid()) {
			facebook_text_txt.setText("You are logged in");
			setUsersDetailsVisibility(true);
			
			setUserNameText(facebook_user);
			
			PreferencesSyncronizer ls = new PreferencesSyncronizer(PreferencesActivity.this);
			ls.GetLikes(facebook_mail, facebook_user);

			if ((picURL != null) && (!picURL.isEmpty())) {
				BitmapSyncronizer cs = new BitmapSyncronizer(
						PreferencesActivity.this);
				cs.getBitmap(picURL);
			}
		} else {
			facebook_text_txt.setText("You are logged out!");
			editor = prefs.edit();
			editor.putString(PREF_FACEBOOK_USER, "");
			editor.putString(PREF_FACEBOOK_MAIL, "");
			editor.putString(PROFILE_PIC_URL, "");
			editor.putString(PROFILE_PIC_URL_SMALL, "");
			editor.putString(PREF_FACEBOOK_PAGE_URL, "");
			editor.putString(PREF_LIKES, "");
			editor.commit();
		}
	}

//	private void savePreferences() {
//
//		int moneyThr = (int) money_thr_ratingbar.getRating();
//		int ratingThr = (int) rating_thr_ratingbar.getRating();
//
//		Editor editor = prefs.edit();
//		editor.putInt(PREF_RATING_THREHOLD, ratingThr);
//		editor.putInt(PREF_MONEY_THREHOLD, moneyThr);
//		Log.i("Preferences", "!!!Saving Buttons!!!");
//		Log.i("Preferences", "Eat button is " + isEatVisible);
//		Log.i("Preferences", "Drink button is " + isDrinkVisible);
//		editor.putBoolean(PREF_DRINK_BUTTON_VISIBLE, isDrinkVisible);
//		editor.putBoolean(PREF_EAT_BUTTON_VISIBLE, isEatVisible);
//		editor.putBoolean(PREF_PARTY_BUTTON_VISIBLE, isPartyVisible);
//		editor.commit();
//	}

	public class SampleAuthListener implements AuthListener {

		public void onAuthSucceed() {
			facebook_text_txt.setText("Logging in ...");
			Bundle params = new Bundle();
			params.putString("fields", "name,email,picture,link");
			mAsyncRunner.request("me", params, new SampleRequestListener());

		}

		public void onAuthFail(String error) {
			facebook_text_txt.setText("Login Failed: " + error);
		}
	}

	public class SampleLogoutListener implements LogoutListener {
		public void onLogoutBegin() {
			facebook_text_txt.setText("Logging out...");
		}

		public void onLogoutFinish() {
			facebook_text_txt.setText("You are logged out! ");
			mUserPic.setImageDrawable(PicturesUtil
					.getUserDefaultPicBig(PreferencesActivity.this));
			setUsersDetailsVisibility(false);
			Editor editor = prefs.edit();
			editor.putString(PREF_FACEBOOK_USER, "");
			editor.putString(PREF_FACEBOOK_MAIL, "");
			editor.putString(PREF_FACEBOOK_PAGE_URL, "");
			editor.putString(PROFILE_PIC_URL, "");
			editor.putString(PROFILE_PIC_URL_SMALL, "");
			editor.putString(PREF_LIKES, "");
			editor.putBoolean(PREF_CHANGED, true);
			editor.commit();
			myDealsList.setAdapter(new BusinessListArrayAdapter(
					PreferencesActivity.this, new ArrayList<Business>()));
		}
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		mFacebook.authorizeCallback(requestCode, resultCode, data);
	}

	public class SampleRequestListener extends BaseRequestListener {

		public void onComplete(final String response, final Object state) {
			try {
				// process the response here: executed in background thread
				Log.d("Facebook-Example", "Response: " + response.toString());
				
				JSONObject json = new JSONObject(response);
				// JSONObject json = Util.parseJson(response);
				final String name = json.getString("name");
				final String mail = json.getString("email");
				final String picURL = json.getString("picture");
				final String profile_id = json.getString("id");
				final String page_link = json.getString("link");

				Editor editor = prefs.edit();
				editor.putString(PREF_FACEBOOK_USER, name);
				editor.putString(PREF_FACEBOOK_MAIL, mail);
				editor.putString(PROFILE_PIC_URL_SMALL, picURL);
				editor.putString(PREF_FACEBOOK_PAGE_URL, page_link);
				editor.putBoolean(PREF_CHANGED, true);
				editor.putString(PROFILE_PIC_URL, "http://graph.facebook.com/" +
							profile_id + "/picture?type=large");
				editor.commit();
				
				mAsyncRunner.request("me/likes", new LikesRequestListener(),null);
				//mAsyncRunner.request("me/interests", new LikesRequestListener(),null);
				
				// then post the processed result back to the UI thread
				// if we do not do this, an runtime exception will be generated
				// e.g. "CalledFromWrongThreadException: Only the original
				// thread that created a view hierarchy can touch its views."

				PreferencesActivity.this.runOnUiThread(new Runnable() {
					public void run() {
						facebook_text_txt.setText("You are logged in");
						setUsersDetailsVisibility(true);
						facebook_user = name;
						facebook_mail = mail;
						
						setUserNameText(facebook_user);
						
						PreferencesSyncronizer ls = new PreferencesSyncronizer(PreferencesActivity.this);
						ls.GetLikes(facebook_mail, facebook_user);
						
						BitmapSyncronizer cs = new BitmapSyncronizer(
								PreferencesActivity.this);
						//cs.getBitmap(picURL);
						cs.getBitmap("http://graph.facebook.com/" +
						profile_id + "/picture?type=large");
						dbc.sync(facebook_mail);
					}
				});

			} catch (JSONException e) {
				Log.w("Facebook-Example", "JSON Error in response");
			}
		}
	}

	
	public class LikesRequestListener extends BaseRequestListener {

		public void onComplete(final String response, final Object state) {
			try {
				// process the response here: executed in background thread
				Log.d("Facebook-Likes/Interests", "Response: " + response.toString());
				JSONObject json = new JSONObject(response);				
				JSONArray  data = json.getJSONArray("data");
				List<String> like_list = new ArrayList<String>();
				for(int i=0;i < data.length();i++){                      
					JSONObject e = data.getJSONObject(i);
					Log.d("Facebook-Likes/Interests", "Adding : " + e.getString("name"));
					like_list.add(e.getString("name"));
				}

				PreferencesSyncronizer ls = new PreferencesSyncronizer(PreferencesActivity.this);
				ls.SendLikes(facebook_mail, facebook_user,like_list);
				
//				PreferencesActivity.this.runOnUiThread(new Runnable() {
//					public void run() {
//						setUsersDetailsVisibility(true);
//						PreferencesSyncronizer ls = new PreferencesSyncronizer(PreferencesActivity.this);
//						ls.GetLikes(facebook_mail, facebook_user);
//					}
//				});

			} catch (JSONException e) {
				Log.w("Facebook-Example", "JSON Error in response");
			}
		}
	}

	public void setUserNameText(String userName) {
		userNameText.setText(userName);
	}

	public void setUserDealsText(int dealsNum) {
		if (dealsNum == 0)
		{
			userDealText.setText("Has offered no deals");
		}
		else if (dealsNum == 1)
		{
			userDealText.setText("Has offered " + dealsNum + " deal");
		}
		else 
		{
			userDealText.setText("Has offered " + dealsNum + " deals");
		}
		
	}

	public void setUserLikesText(List<String> strings) {
		String tempStr = "Likes: ";
		for (int i = 0; i <= strings.size() - 2; i++) {
			tempStr += strings.get(i) + ", ";
		}
		tempStr += strings.get(strings.size() - 1);
		userLikesText.setText(tempStr);
	}

	public void setUsersDetailsVisibility(boolean b) {
		if (b)
			userDetailsLayout.setVisibility(ViewGroup.VISIBLE);
		else
			userDetailsLayout.setVisibility(ViewGroup.GONE);
	}

	@Override
	public void onResume() {
		super.onResume();
		if (mFacebook != null && !mFacebook.isSessionValid()) {
			facebook_text_txt.setText("You are logged out! ");
			mUserPic.setImageDrawable(PicturesUtil.getUserDefaultPicBig(this));
			setUsersDetailsVisibility(false);
		}
	}
}
